const generate = require('nanoid/generate')
const generateUuid = function () {
  return generate('1234567890abcdef', 10);
};
export default {
  // 选中元件与取消选中
  select(state, payload) {
    state.uuid = payload.uuid;
    if (payload.uuid === -1) {
      state.activeElement = state.page;
      state.type = 'page'
    } else {
      let widget = state.widgets.find(w => w.uuid === payload.uuid);
      state.activeElement = widget;
      state.type = widget.type;

      widget.draggable = true;
      if (widget.parent) { //如果是容器内的组件，防止拖动时容器也跟着移动，把容器禁止拖动
        let parent = state.widgets.find(w => w.uuid === widget.parent);
        parent.draggable = false;
      }
    }
  },
  dragStart(state, payload) {
    let widget = state.widgets.find(w => w.uuid === payload.uuid);
    widget.draggable = true;
  },

  // 设置 mousemove 操作的初始值
  initmove(state, payload) {
    state.startX = payload.startX;
    state.startY = payload.startY;
    state.originX = payload.originX;
    state.originY = payload.originY;
    state.moving = true
  },

  // 元件移动结束
  stopmove(state) {
    state.moving = false
  },

  // 移动元件
  move(state, payload) {
    const target = state.activeElement;
    /*let dx = payload.x - state.startX
    let dy = payload.y - state.startY
    let left = state.originX + Math.floor(dx * 100 / state.zoom)
    let top = state.originY + Math.floor(dy * 100 / state.zoom)

    target.left = left > 0 ? left : 0
    target.top = top > 0 ? top : 0*/

    target.x = payload.x;
    target.y = payload.y;

  },

  // 调整元件尺寸
  resize(state, payload) {
    const target = state.activeElement;
    target.x = payload.x;
    target.y = payload.y;
    target.w = payload.w;
    target.h = payload.h;


    /*let dx = payload.x - state.startX
    let dy = payload.y - state.startY
    let value

    if (payload.type === 'right') {
      value = state.originX + Math.floor(dx * 100 / state.zoom)
      state.activeElement.width = value > 10 ? value : 10
      return
    }

    if (payload.type === 'down') {
      value = state.originX + Math.floor(dy * 100 / state.zoom)
      state.activeElement.height = value > 10 ? value : 10
      return
    }

    if (payload.type === 'left') {
      let left = state.originX + Math.floor(dx * 100 / state.zoom)
      let width = state.originY - Math.floor(dx * 100 / state.zoom)
      state.activeElement.left = left > 0 ? left : 0
      state.activeElement.width = width > 10 ? width : 10
      return
    }

    if (payload.type === 'up') {
      let top = state.originX + Math.floor(dy * 100 / state.zoom)
      let height = state.originY - Math.floor(dy * 100 / state.zoom)
      state.activeElement.top = top > 0 ? top : 0
      state.activeElement.height = height > 10 ? height : 10
    }*/
  },

  // 复制元件
  copy(state, payload) {
    if (state.type !== 'page') {
      let copy = Object.assign({}, state.activeElement, {top: state.top, uuid: generateUuid()});

      // 由于容器的名称必须是唯一的，故复制容器需作处理
      if (state.activeElement.isContainer) {
        let name = state.activeElement.name;
        if (name) {
          // 设置容器副本的名称
          let copyName = name.split('-')[0] + '-' + state.counter;
          copy.name = copyName;

          // 复制容器内的图片和文本
          for (let i = 0, len = state.widgets.length; i < len; i++) {
            if (state.widgets[i].belong === name) {
              state.widgets.push(
                Object.assign({}, state.widgets[i], {belong: copyName})
              )
            }
          }

          state.counter += 1
        }
      }

      state.widgets.push(copy)
    }
  },

  // 更新元件初始 top 值
  updateSrollTop(state, top) {
    state.top = top
  },

  // 页面缩放
  zoom(state, val) {
    state.zoom = val
  },

  // 初始化选中对象
  initActive(state) {
    state.activeElement = state.page
  },

  // 删除选中元件
  delete(state) {
    let type = state.type;
    if (type === 'page') return;

    // 如果删除的是容器，须将内部元件一并删除
    if (state.activeElement.isContainer) {
      let name = state.activeElement.name;

      for (let i = 0; i < state.widgets.length; i++) {
        if (state.widgets[i].belong === name) {
          state.widgets.splice(i, 1)
        }
      }
    }

    // 删除元件
    for (let i = 0; i < state.widgets.length; i++) {
      if (state.widgets[i].uuid === state.activeElement.uuid) {
        state.widgets.splice(i, 1);
      }
    }

    // 重置 activeElement
    state.activeElement = state.page;
    // state.type = 'page'
    state.uuid = -1
  },

  // 添加组件
  addWidget(state, {data: data = null, item}) {

    let setting = JSON.parse(JSON.stringify(item.setting));
    setting.uuid = generateUuid();
    if (!setting.z) {
      setting.z = 1;
    }
    if (!setting.dataSource) {
      setting.dataSource = {};
    }
    if (setting.isContainer) {
      setting.name = setting.uuid;
    }

    if (data) {
      data.forEach(function (val) {
        state.widgets.push(Object.assign(setting, val))
      })
    } else {
      state.widgets.push(Object.assign(setting))
    }
  },

  // 替换图片
  replaceImage(state, payload) {
    state.activeElement.width = payload[0].width;
    state.activeElement.url = payload[0].url;
  },

  // 添加容器背景图
  addContainerBackPic(state, payload) {
    state.activeElement.backPic = payload[0].url;
    state.activeElement.backPicUrl = payload[0].src;
    state.activeElement.width = payload[0].width;
    state.activeElement.height = payload[0].height;
  },

  // 添加背景图
  addBackPic(state, payload) {
    state.activeElement.backPic = payload[0].url;
    state.activeElement.backPicUrl = payload[0].src;
  },

  // 添加动画
  addAnimation(state) {
    state.animation.push({
      name: '',
      duration: 3,
      delay: 0,
      iteration: 1,
      timing: 'linear',
      direction: 'normal',
      fill: 'none',
      keyframes: [
        {
          stop: 0,
          css: ''
        }
      ]
    })
  },

  // 为动画添加 keyframe
  addkeyframe(state, name) {
    state.animation.map(val => {
      if (val.name === name) {
        val.keyframes.push({
          stop: 0,
          css: ''
        })
      }
    })
  },

  // 动画的播放与停止
  setAnimation(state, status) {
    state.playState = status
  },

  // 更新数据
  updateData(state, {uuid, key, value}) {
    let widget = state.widgets.find(w => w.uuid === uuid);
    widget[key] = value
  },

  //更新数据源
  dataSource(state, {uuid, dataSource}) {
    let widget = state.widgets.find(w => w.uuid === uuid);
    widget.dataSource = dataSource;
  },

  //添加全局数据源
  globalDataSource(state, data) {
    if (data.uuid) { //更新
      let ds = state.dataSources.find(w => w.uuid === data.uuid);
      Object.assign(ds, data);
    } else { //新增
      data.uuid = generateUuid();
      state.dataSources.push(data);
    }

  },
  //删除全局数据源
  delGlobalDataSource(state, index) {
    state.dataSources.splice(index, 1);
  },

  scroll(state, {left, top}) {
    state.page.scrollLeft = left;
    state.page.scrollTop = top;
  },

  //新增/修改行为
  saveAction(state, {uuid, action}) {
    let widget = state.widgets.find(w => w.uuid === uuid);
    if (!widget) {
      return;
    }
    if (action.uuid) {
      widget.actions.forEach((item, index) => {
        if (item.uuid === action.uuid) {
          widget.actions.splice(index, 1, action)
        }
      })
    } else {
      const actions = widget.actions || [];
      action.uuid = generateUuid();
      actions.push(action);
      widget.actions = actions;
    }
  },
  //删除行为
  delAction(state, {uuid, action}) {
    let widget = state.widgets.find(w => w.uuid === uuid);
    if (!widget) {
      return;
    }
    widget.actions.forEach((item, index) => {
      if (item.uuid === action.uuid) {
        widget.actions.splice(index, 1);
      }
    })
  },

  /**
   * 设置加载的数据
   */
  setLoadedData(state, {key, data}) {
    state.loadedData[key] = data;
  },

  /**
   * 修改页面上组件的uuid
   */
  updateUuid(state, {uuid, newUuid}) {
    let widget = state.widgets.find(w => w.uuid === uuid);
    widget.uuid = newUuid;
  }
}
